import { useRef, useEffect } from "react";
import moment from "moment";

export default function Clock() {

    const ref = useRef()

    const drawDial = () => {
        const context = ref.current.getContext('2d')
        context.clearRect(0, 0, ref.current.width, ref.current.height)

        const margin = 40
        const radius = ref.current.width / 2 - margin
        const x = ref.current.width / 2, y = ref.current.height / 2

        context.strokeStyle = 'black'
        // 圆盘
        context.beginPath()
        context.arc(x, y, radius, 0, 2 * Math.PI, true)
        context.lineWidth = 2
        context.stroke()
        context.closePath()

        // 圆心
        context.beginPath()
        context.arc(x, y, 5, 0, 2 * Math.PI)
        context.fillStyle = 'black'
        context.fill()
        context.stroke()
        context.closePath()

        // 刻度
        context.beginPath()
        const degree = 2 * Math.PI / 12 // 时针一个刻度30°
        const scaleMargin = 20
        for (let i = 1; i <= 12; i++) {
            let angle = degree * (i - 3) // 从横轴x=0位置开始画, -3代表从3点钟方向逆时针旋转90°至12点方向
            context.font = '15px Arial'
            context.fillText(i.toString(), x + (radius + scaleMargin) * Math.cos(angle), y + (radius + scaleMargin) * Math.sin(angle))
        }
        context.closePath()

        const hour = moment().hour() - 3,
            minute = moment().minute(),
            second = moment().second()

        // 绘制时针
        context.beginPath()
        context.moveTo(x, y)
        const hourHandRadius = radius - 40, hourHandLineWidth = 5
        context.lineTo(x + hourHandRadius * Math.cos(degree * hour), y + hourHandRadius * Math.sin(degree * hour))
        context.lineWidth = hourHandLineWidth
        context.stroke()
        context.closePath()


        // 绘制分针
        context.beginPath()
        context.moveTo(x, y)
        const degree2 = 2 * Math.PI / 60 // 分针、秒针一个刻度6°
        const minuteHandRadius = radius - 20, minuteHandLineWidth = 8
        context.lineTo(x + minuteHandRadius * Math.cos(degree2 * minute - Math.PI / 2), y + minuteHandRadius * Math.sin(degree2 * minute - Math.PI / 2))
        context.lineWidth = minuteHandLineWidth
        context.stroke()
        context.closePath()

        //绘制秒针
        context.beginPath()
        context.moveTo(x, y)
        const secondHandRadius = radius - 10, secondHandLineWidth = 2
        context.lineTo(x + secondHandRadius * Math.cos(degree2 * second - Math.PI / 2), y + secondHandRadius * Math.sin(degree2 * second - Math.PI / 2))
        context.lineWidth = secondHandLineWidth
        context.strokeStyle = 'red'
        context.stroke()
        context.closePath()

    }

    useEffect(() => {
        setInterval(() => {
            drawDial()
        }, 1000)
        // drawDial()
    }, [])

    return (
        <div>
            <canvas width={400} height={400} ref={ref}></canvas>
        </div>
    )
}